package com.zixuan.sina.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.zixuan.sina.dao.RoleMapper;
import com.zixuan.sina.entity.Role;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.service.RoleService;
import com.zixuan.sina.service.UserService;
import com.zixuan.sina.utils.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserService userService;
    @Override
    public Result getRoleList(String roleName) {
        List<Role> roleList = roleMapper.getRoleList(roleName);
        //查出id对应的nickname
        roleList =roleList.stream().map(m->{
            User userById = userService.findUserById(m.getCreateUser().toString());
            if(ObjectUtil.isNotNull(userById)){
                m.setNickName(userById.getNickName());
            }
            return m;
        }).collect(Collectors.toList());
        return Result.ok(roleList);
    }

    @Override
    public List<Long> getPermissionListByRoleId(String roleId) {
        return roleMapper.getRoleListIds(roleId);
    }

    @Override
    public int addPermission(String roleId, List<Long> permissionIds) {
        //先删除权限
        roleMapper.deletePermission(roleId);
        //再添加权限
        int row=0;
//        permissionIds.add(1L);
//        permissionIds.add(2L);
        for (Long permissionId : permissionIds) {
             row =roleMapper.addPermission(roleId,permissionId);
        }

        return row;
    }

    @Override
    public Long getRoleById(Long userId) {

        return roleMapper.getRoleById(userId);
    }

    @Override
    public int assign(Long userId, Long roleId) {
        //先删除
        roleMapper.deleteRole(userId);
        //再新增
        return roleMapper.assign(userId,roleId);
    }
}
